package com.example.oom;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class DirectMemoryOOM {

    public static void main(String[] args) {
        System.out.println("开始模拟 Direct buffer memory OOM...");

        // 用于保存引用，防止 ByteBuffer 被 GC 回收
        List<ByteBuffer> buffers = new ArrayList<>();

        int count = 0;
        try {
            while (true) {
                // 每次分配 10MB 直接内存
                ByteBuffer buffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
                buffers.add(buffer);

                count++;
                if (count % 10 == 0) {
                    System.out.println("已分配 " + (count * 10) + " MB 直接内存");
                }
            }
        } catch (OutOfMemoryError e) {
            System.err.println("触发 Direct buffer memory OOM!");
            e.printStackTrace();
            System.out.println("总共分配次数: " + count);
        }
    }
}
